<template>
  <tl-sub-page :render="render" :with-header="false" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-drawer" :size="size" @open="open" @close="close" :destroy-on-close="true" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true">
    <div class="project-container">
      <div class="customer-header">
        <div class="info">
          <img src="/static/images/paojectManager/mpm_plan_edit.png" class="logo" style="width: 55px;height: 55px" />
          <div class="content" :title="projectinfo.projectname">
            <p>
              <b style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;width: 52%;">{{ projectinfo.projectname }}</b>
            </p>
            <p class="light">
              <span>项目经理：{{ projectinfo.projectmanager }}</span>
              <span>项目编号：{{ projectinfo.projectcode ? projectinfo.projectcode : '暂无' }}</span>
              <span>项目级别：{{ projectinfo.dispprojectlevel ? projectinfo.dispprojectlevel : '暂无' }}</span>
              <span v-if="model.createon">创建时间：{{ formatDate(model.createon) }}</span>
            </p>
          </div>
        </div>
        <!-- <div class="toolbar" style="margin-top: 10px;">
          <el-button type="danger" size="small" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div> -->
        <div class="toolbar">
          <el-button type="danger" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div>
      </div>
      <div class="project-nav" :style="{ height: mainHeight + 'px' }">
        <ul class="nav-list" style="top:0px">
          <template v-for="item in navList">
            <li :key="item.code" v-if="item.show" :class="item.on ? 'on' : ''" @click="clickNav(item.code)" style="cursor: pointer;clear: both">
              <span style="float: left;width: 100px">{{ item.name }}</span>
              <span style="float: left;">
                <i v-if="item.count > 0">{{ item.count }}</i>
                <label v-if="item.flag">{{ item.flag }}</label>
              </span>
            </li>
          </template>
        </ul>
      </div>
      <!-- <el-row v-if="fromApproval === '1'">
      <el-col :span="24">
        <el-button type="danger" style="float: right" size="small" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
      </el-col>
    </el-row> -->
      <div class="project-main" :style="{ height: mainHeight + 'px' }">
        <el-scrollbar class="customer-main-container" id="customerMainContainer">
          <div style="padding:0 10px">
            <!-- <a id="baseinfo" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                基本信息
              </div>
              <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="变更内容" prop="changecontent" v-if="displayChangeReasonFlag" :rules="rules.validateRequire">
                      <el-input type="textarea" show-word-limit maxlength="1000" :rows="4" v-model="model.changecontent"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="变更原因" prop="changereason" v-if="displayChangeReasonFlag" :rules="rules.validateRequire">
                      <el-input type="textarea" show-word-limit maxlength="1000" :rows="4" v-model="model.changereason"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="策划书名称" prop="proposalname" :rules="rules.validateRequire">
                      <el-input v-model="model.proposalname" :disabled="true"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="策划书编号" prop="proposalcode">
                      <el-input v-model="model.proposalcode" :disabled="true" placeholder="系统自动生成"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="策划书描述" prop="plandescription" :rules="rules.validateRequire">
                      <el-input v-model="model.plandescription" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div> -->
            <!-- <a id="background" class="step-position">&nbsp;</a> -->
            <a id="baseinfo" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                基本信息
              </div>
              <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="变更内容" prop="changecontent" v-if="displayChangeReasonFlag" :rules="rules.validateRequire">
                      <el-input type="textarea" show-word-limit maxlength="1000" :rows="4" v-model="model.changecontent"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="变更原因" prop="changereason" v-if="displayChangeReasonFlag" :rules="rules.validateRequire">
                      <el-input type="textarea" show-word-limit maxlength="1000" :rows="4" v-model="model.changereason"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目背景" prop="projectbackground" :rules="rules.validateRequire">
                      <el-input v-model="model.projectbackground" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请简要陈述项目背景，最多1000字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目目标" prop="projecttarget" :rules="rules.validateRequire">
                      <el-input v-model="model.projecttarget" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请简要陈述项目目标，最多1000字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="总体策划" prop="projectsummary" :rules="rules.validateRequire">
                      <el-input v-model="model.projectsummary" type="textarea" :rows="4" maxlength="1000" placeholder="请简要陈述目标策划，最多1000字。" show-word-limit></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <!-- <a id="implementation" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                项目实施方案
              </div>
              <el-form class="tl-form" ref="form2" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目实施方案" prop="projectimplementation" :rules="rules.validateRequire">
                      <el-input v-model="model.projectimplementation" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请简要陈述项目实施方案，最多500字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div> -->
            <!-- <a id="competitor" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                竞争对手分析
              </div>
              <el-form class="tl-form" ref="form4" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="潜在竞争对手" prop="competitors" :rules="rules.validateRequire">
                      <el-input v-model="model.competitors" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请简要陈述潜在竞争对手，最多500字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <tl-project-competitor ref="projectcompetitor" :parentId="model.id" :editable="!disableSave" :projectinfo="projectinfo" :planstate="model.state"></tl-project-competitor>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="竞争对手策略分析" prop="competitoranalysis" :rules="rules.validateRequire">
                      <el-input v-model="model.competitoranalysis" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请简要陈述竞争对手策略分析，最多500字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="应对策略" prop="copingstrategies" :rules="rules.validateRequire">
                      <el-input v-model="model.copingstrategies" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请简要陈述应对策略，最多500字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div> -->
            <a id="milepost" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-titlemilepost">
                里程碑及任务
              <el-dropdown trigger="hover">
              <el-button type="primary">导入导出</el-button>
              <el-dropdown-menu slot="dropdown" >
                <el-dropdown-item v-if="!disableEditSubmit && !disableSave" @click.native="doexcelImport">导入</el-dropdown-item>
                <el-dropdown-item @click.native="downloadTemplate(templateName, fileName)">下载模板</el-dropdown-item>
                <el-dropdown-item v-if="!isAdd" :loading="saveLoading" @click.native="doExportExcelForPlan">导出</el-dropdown-item>
              </el-dropdown-menu>
              </el-dropdown>
              </div>
              <el-form class="tl-form" style="margin-top:20px" ref="form5" :model="model" :rules="rules" label-width="150px">
                <tl-line v-if="visible" ref="line" :parentId="model.id" :editable="!disableSave" :isshowdisable="disableEditSubmit || disableSave" :projectinfo="projectinfo" :planstate="model.state" :customerTaskFlag="customerTaskFlag" @refresh="refreshForState" :ifFistPlan="!displayChangeReasonFlag" :provincePmChangeFlag="provincePmChangeFlag"></tl-line>
              </el-form>
            </div>
            <a id="customerAnalysis" class="step-position">&nbsp;</a>
            <!-- <div>
              <div class="tl-form-line-title" v-if="customerAFlag || customerBCDFlag">
                客户决策分析
              </div>
              <el-form class="tl-form" ref="form3" :model="model" :rules="rules" label-width="150px">
                <tl-customer-analysis ref="customer" :parentId="model.id" :editable="!disableSave" :projectinfo="projectinfo" :planstate="model.state" v-show="customerBCDFlag"></tl-customer-analysis>
                <tl-customer-task-analysis ref="customerTaskAnalysis" :parentId="model.id" :showDisabled="disableSave || disableEditSubmit" v-show="customerAFlag"></tl-customer-task-analysis>
                // <tl-customer-task ref="customertask" :parentId="model.id"></tl-customer-task>
              </el-form>
            </div> -->
            <a id="docapplyinfo" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                单据信息
              </div>
              <el-form class="tl-form" ref="form6" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="申请部门" prop="applydeptname">
                      <tl-ref-dept v-model="model.applydeptcode" :initDisplayData.sync="model.applydeptname" :disabled="true" dataType="code" nameType="fullname" :singleSelect="true" :externalQueryParam="{ qry_enabled: 1 }"></tl-ref-dept>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="申请公司" prop="applyorgname">
                      <el-input v-model="model.applyorgname" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="申请人姓名" prop="applyusername">
                      <tl-ref-user v-model="model.applyusername" :initDisplayData.sync="model.applyusername" :disabled="true" dataType="code" :singleSelect="true"></tl-ref-user>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="申请人工号" prop="applyusercode">
                      <el-input v-model="model.applyusercode" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="单据日期" prop="docdate">
                      <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="提交时间" prop="submitdate">
                      <el-date-picker v-model="model.submitdate" type="date" placeholder="提交时间" value-format="yyyy-MM-dd" disabled></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="审批流程" prop="flowid">
                      <el-input v-model="model.dispflowid" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="状态" prop="state">
                      <el-input v-model="model.dispstate" disabled></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div slot="footer" class="dialog-footer" style="float:right;margin-top:10px">
              <!-- <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button> -->
              <el-button @click="doSubmitEdit" :loading="saveLoading || submitLoading" icon="el-icon-document-checked" type="primary" :disabled="disableSave" v-if="!disableEditSubmit">保存</el-button>
              <el-button @click="doSubmitApproval" :loading="saveLoading || submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval" type="primary"> <svg-icon icon-class="send" />提交审批 </el-button>
              <tl-attachment ref="attachmentRef" sourceType="MpmProjectPlan" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit">
                <el-button type="primary" :disabled="disableAttachment" icon="el-icon-paperclip" @click="$refs.attachmentRef.openUploadDialog()">{{ this.$refs.attachmentRef ? this.$refs.attachmentRef.btnTitle : '' }} [{{ this.$refs.attachmentRef ? (this.$refs.attachmentRef.fileList.length > 0 ? this.$refs.attachmentRef.fileList.length : this.$refs.attachmentRef.fileCount) : 0 }}] </el-button>
              </tl-attachment>
              <el-button @click="$refs.history.visible = true" :disabled="disableApprovalHistory" type="primary"> <svg-icon icon-class="list" />审批历史 </el-button>
              <el-button @click="doDelApproval" :loading="delApprovalLoading" :disabled="disableDelApproval" type="primary"> <svg-icon icon-class="undo" />审批退回 </el-button>
            </div>
            <tl-approval-history ref="history" sourceType="MpmProjectPlan" :sourceId="model.id" />
          </div>
        </el-scrollbar>
      </div>
    </div>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
import { mixin_download_template } from '@/mixins/mixin_download_template'
/** 子组件 */
import tlLine from '../mpmProjectMilepost/indexFrame'
import tlCustomerAnalysis from '../mpmCustomerAnalysis/indexFrame'
import tlProjectCompetitor from '../mpmProjectCompetitor/indexFrame'
import tlCustomerTaskAnalysis from '../mpmCustomerAnalysis/indexView'
import { mixin_page_fields_custom } from '@misui/mixins/mixin_page_fields_custom'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { formatDate } from '@tapui/utils/date'
import { validateNull } from '@tapui/utils/validate'
import { exportExcel, exportExcelAxio } from '@tapui/api/office'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit, mixin_page_fields_custom, mixin_download_template],
  components: { tlLine, tlCustomerAnalysis, tlProjectCompetitor, tlCustomerTaskAnalysis },
  data() {
    return {
      moduleTitle: '项目策划',
      urlPrefix: '/mpm/projectPlan/',
      url: {
        // 额外的url
        checkProjectALevel: '/mpm/projectPlan/checkProjectALevel',
        exportBigExcel: '/mpm/projectPlan/exportBigExcel',
        downloadTemplate: '/mpm/projectBidScore/downloadTemplate'
      },
      activeTabName: 'basic',
      isRefreshLine: false,
      count: 0,
      planInfo: {},
      navList: [
        { name: '基本信息', count: 0, flag: null, on: true, code: 'baseinfo', show: true },
        // { name: '背景策略', count: 0, flag: null, on: true, code: 'background', show: true },
        // { name: '项目实施方案', count: 0, flag: null, on: true, code: 'implementation', show: true },
        // { name: '竞争对手分析', count: 0, flag: null, on: true, code: 'competitor', show: true },
        { name: '里程碑及任务', count: 0, flag: null, on: true, code: 'milepost', show: true },
        // { name: '客户决策分析', count: 0, flag: null, on: true, code: 'customerAnalysis', show: true },
        { name: '单据信息', count: 0, flag: null, on: true, code: 'docapplyinfo', show: true }
      ],
      fromApproval: '',
      size: '95%',
      mainHeight: 100,
      displayChangeReasonFlag: false,
      projectALevelFlag: false,
      provincePmFlag: false,
      templateName: 'milepostTemplate.xlsx',
      fileName: '销售项目WBS分解模板.xlsx',
      cols: "milepostname;里程碑及主任务,planfinishtime;计划达成日期,deliverable;交付成果,responsible;里程碑主任务责任人," +
      "taskname;分任务名称,tasktarget;任务目标,taskdetail;任务内容,taskresponsible;任务责任人,planstartdate;计划开始时间,planenddate;计划完成时间," +
      "post;关键决策客户部门职务,dispcustomerapproval;任务支撑程度,customerattach;客户接触现状,improveplan;客户改善计划,dispneedsupport;是否需要系统部支持"
    }
  },
  computed: {
    customerAFlag() {
      return this.model.oldplanflag === 0 && this.model.oldplanflagsecond === 1 && this.projectALevelFlag
    },
    customerBCDFlag() {
      return !this.projectALevelFlag || (this.model.oldplanflag === 1 && this.model.oldplanflagsecond === 1 && this.projectALevelFlag)
    },
    customerTaskFlag() {
      return this.model.oldplanflagsecond === 0 && this.projectALevelFlag
    },
    // A级项目、项目经理为省总，处在变更阶段
    provincePmChangeFlag() {
      return this.provincePmFlag && this.displayChangeReasonFlag
    }
  },
  props: {
    render: {
      default: 'el-drawer',
      type: String
    },
    projectinfo: {},
    oldmilepost: []
  },
  methods: {
    /** 保存确认 */
    doSubmitEdit() {
      if (!this.beforeSubmit()) {
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
        } else {
          return false
        }
      })
    },
    doExportExcelForPlan() {
      let data = {
        planid: this.model.id,
        projectcode: this.model.projectcode,
        cols: this.cols
      }
      exportExcelAxio({ url: this.url.exportBigExcel, data: data }).then((res) => {
        var reader = new FileReader()
        reader.readAsText(res.data, 'utf-8')
        reader.onload = () => {
          try {
            var info = JSON.parse(reader.result)
            this.$tap.alert(info.message)
          } catch (e) {
            var isTaskExport = res.headers.istaskexport
            if (isTaskExport === '1') {
              this.$tap.alert('系统正在导出，请到excel导出任务页面下载')
            } else {
              var blob = new Blob([res.data], { type: 'application/octet-stream;charset=utf-8' })
              var filename = decodeURI(res.headers['filename'])
              if (typeof filename === 'undefined') {
                filename = '导出数据.xlsx'
              }
              var tempObjectUrl = window.URL.createObjectURL(blob)
              var aLink = document.createElement('a')
              aLink.style.display = 'none'
              aLink.download = filename
              aLink.href = tempObjectUrl
              document.body.appendChild(aLink)
              aLink.click()
              document.body.removeChild(aLink)
              window.URL.revokeObjectURL(tempObjectUrl)
            }
          }
        }
      })
      .catch((error) => {
        this.$tap.alert(error, 'warning')
      })
    },
    // 当更新了项目状态时回调
    refreshForState() {
      this.$emit('refresh')
    },
    formatDate(date) {
      return formatDate(new Date(date ? date.toString().replace(/\-/g, '/') : date), 'yyyy-MM-dd HH:mm')
    },
    // 点击左侧导航
    clickNav(code) {
      this.navList.forEach((m) => {
        if (m.code === code) {
          m.on = true
        } else {
          m.on = false
        }
      })
      let element = document.getElementById(code)
      if (element === null) return
      let goY = element.getBoundingClientRect().y - 75
      this.mainScrollElement.scrollTop += goY
    },
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100
    },
    // 页面滚动时，动态改变左侧导航选中的元素
    onMainScroll() {
      this.mainScrollElement.addEventListener('scroll', () => {
        let currentTop = this.mainScrollElement.scrollTop
        let code = ''
        for (let element of document.getElementsByClassName('step-position')) {
          if (element.getBoundingClientRect().y >= 0) {
            code = element.id
            break
          }
        }
        this.navList.forEach((m) => {
          if (m.code === code) {
            m.on = true
          } else {
            m.on = false
          }
        })
      })
    },
    assignDefaultValue() {
      if (this.isAdd) {
        this.$set(this.model, 'proposalname', this.projectinfo.projectname + '策划书')
        this.$set(this.model, 'projectcode', this.projectinfo.projectcode)
        this.$set(this.model, 'projectname', this.projectinfo.projectname)
        this.$set(this.model, 'applyorgcode', this.org.code)
        this.$set(this.model, 'applyorgname', this.org.name)
        this.$set(this.model, 'applydeptcode', this.dept.code)
        this.$set(this.model, 'applydeptname', this.dept.fullname)
        this.$set(this.model, 'applyusercode', this.user.code)
        this.$set(this.model, 'applyusername', this.user.name)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'docdate', new Date())
        this.$set(this.model, 'deptcode', this.projectinfo.deptcode)
        this.$set(this.model, 'oldplanflag', 0)
        this.$set(this.model, 'oldplanflagsecond', 0)
      }
    },
    created() {
      window.addEventListener('resize', this.resizeHandler)
    },
    checkplancount() {
      let param = {}
      if (this.isAdd) {
        param = {
          projectcode: this.projectinfo.projectcode,
          isadd: this.isAdd
        }
      } else {
        param = {
          projectcode: this.projectinfo.projectcode,
          isadd: this.isAdd,
          id: this.model.id
        }
      }
      getAction('/mpm/projectPlan/checkplancount', param).then((res) => {
        if (res.success) {
          this.displayChangeReasonFlag = !res.result.isFirstPlan
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    open() {
      this.navList.forEach(function(item, index) {
        if (index === 0) {
          item.on = true
        } else {
          item.on = false
        }
      })
      this.model = {}
      this.resizeHandler()
      this.$nextTick(() => {
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          // this.loadData()
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.loaded()
              this.addDefaultValue()
              // this.doAdd()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
            this.addDefaultValue()
            // this.doAdd()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
            this.$refs.line.milepostLoadInfo()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
            this.$refs.line.milepostLoadInfo()
          })
        }
      })
      this.$nextTick(() => {
        this.mainScrollElement = document.getElementById('customerMainContainer').getElementsByClassName('el-scrollbar__wrap')[0]
        this.onMainScroll()
      })
    },
    close() {
      this.$emit('refresh')
      this.displayChangeReasonFlag = false
      this.model = {}
    },
    loaded() {
      // 页面加载完毕执行
      this.activeTabName = 'basic'
      this.isRefreshLine = false
      // debugger
      // this.$refs.customer.loadData()
      // this.$refs.customerTaskAnalysis.loadData()
      // this.$refs.projectcompetitor.loadData()
      // this.$refs.form.clearValidate()
      this.$refs.form.clearValidate()
      // this.$refs.form2.clearValidate()
      // this.$refs.form4.clearValidate()
      // this.$refs.line.loadData()
      this.checkplancount()
      this.checkProjectALevel()
    },
    // 同步项目立项相同字段 并保存
    addDefaultValue() {
      const { projectcode } = this.model
      const param = {
        qry_projectcode: projectcode,
        qry_enabled: 1,
        qry_state: 9,
        sidx: 'createon',
        sord: 'desc',
        pageSize: 10,
        currentPage: 1
      }
      getAction('/mpm/projectPlan/list', param).then((res) => {
        if (res.success) {
          if (res.result.dataList.length !== 0) {
            this.$set(this.model, 'plandescription', res.result.dataList[0].plandescription)
            this.$set(this.model, 'projectbackground', res.result.dataList[0].projectbackground)
            this.$set(this.model, 'projecttarget', res.result.dataList[0].projecttarget)
            this.$set(this.model, 'projectimplementation', res.result.dataList[0].projectimplementation)
            this.$set(this.model, 'competitors', res.result.dataList[0].competitors)
            this.$set(this.model, 'competitoranalysis', res.result.dataList[0].competitoranalysis)
            this.$set(this.model, 'copingstrategies', res.result.dataList[0].copingstrategies)
            this.$set(this.model, 'projectsummary', res.result.dataList[0].projectsummary)
            var a = res.result.dataList[0].proposalcode
            if (a.length <= 10) {
              this.$set(this.model, 'proposalcode', a + '-2')
            } else {
              let b = parseInt(a.substring(a.lastIndexOf('-') + 1)) + 1
              this.$set(this.model, 'proposalcode', a.substring(0, a.lastIndexOf('-') + 1) + b)
            }
          } else {
            this.$set(this.model, 'projectbackground', this.projectinfo.background)
            // this.$set(this.model, 'projecttarget', '目标：' + this.projectinfo.target + '\n策略：' + this.projectinfo.summary)
            this.$set(this.model, 'projecttarget', this.projectinfo.target)
            this.$set(this.model, 'projectsummary', this.projectinfo.summary)
          }
          // 临时字段 用来同步初始里程碑及任务
          this.$set(this.model, 'firstAdd', 1)
          // 保存策划书
          this.doAdd()
          // 同步里程碑及任务
          // this.$nextTick((_) => {
          //   this.$refs.line.updateInfo()
          // })
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    async afterSubmit() {
      await this.insertBatch()
    },
    checkProjectALevel() {
      getAction(this.url.checkProjectALevel, { projectcode: this.model.projectcode }).then((res) => {
        if (res.success) {
          this.projectALevelFlag = res.result.alevelflag
          this.provincePmFlag = res.result.managerflag
          if (this.model.oldplanflagsecond === 0 && this.projectALevelFlag && this.navList.length > 5) {
            // 不显示客户决策分析左侧栏
            this.$set(this.navList[5], 'show', false)
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    // 同步旧策划书 里程碑及任务,为初始策划书添加默认标前引导里程碑及任务
    async insertBatch() {
      // 新增的标记firstAdd，新增的第一次保存firstAdd值为1
      if (this.model.firstAdd === 1) {
        var datamap = {
          oldmilepost: this.oldmilepost,
          projectcode: this.projectinfo.projectcode,
          projectlevel: this.projectinfo.projectlevel,
          projectname: this.projectinfo.projectname,
          planid: this.model.id
        }
        postAction('mpm/projectMilepost/insertBatch', datamap).then((res) => {
          if (res.success) {
            this.$refs.line.milepostLoadInfo()
            // this.$refs.customer.loadData()
            // this.$refs.projectcompetitor.loadData()
            // this.$refs.customerTaskAnalysis.loadData()
            this.model.firstAdd = 0
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      } else {
        await this.$refs.line.updateInfo()
        await this.$refs.line.milepostLoadInfo()
        // await this.$refs.line.updateInfo().then(() => {
        //   this.$refs.line.milepostLoadInfo()
        // })
      }
    },
    beforeApproval() {
      if (this.displayChangeReasonFlag && (this.model.changereason === undefined || this.model.changereason === null || this.model.changereason === '')) {
        this.$tap.alert('请填加变更内容及原因！', 'warning')
        this.submitLoading = false
        return false
      }
      if (this.model.projectbackground === undefined || this.model.projectbackground === null || this.model.projectbackground === '') {
        this.$tap.alert('请填加项目背景！', 'warning')
        this.submitLoading = false
        return false
      }
      if (this.model.projecttarget === undefined || this.model.projecttarget === null || this.model.projecttarget === '') {
        this.$tap.alert('请填加项目目标！', 'warning')
        this.submitLoading = false
        return false
      }
      if (this.model.projectsummary === undefined || this.model.projecttarget === null || this.model.projecttarget === '') {
        this.$tap.alert('请填加总体策划！', 'warning')
        this.submitLoading = false
        return false
      }
      // if (this.model.projectimplementation === undefined || this.model.projectimplementation === null || this.model.projectimplementation === '') {
      //   this.$tap.alert('请填加项目实施方案！', 'warning')
      //   this.submitLoading = false
      //   return false
      // }
      if (this.$refs.line) {
        if (this.$refs.line.milepostList.length === 0) {
          this.$tap.alert('请添加里程碑及任务，添加里程碑及任务后再提交审批！', 'warning')
          this.submitLoading = false
          return false
        }
        for (let i = 0; i < this.$refs.line.milepostList.length; i++) {
          let item = this.$refs.line.milepostList[i]
          if (item.milepostname === null || item.milepostname === undefined || item.milepostname === '' || item.planfinishtime === null || item.planfinishtime === undefined || item.planfinishtime === '' || item.responsiblecode === null || item.responsiblecode === undefined || item.responsiblecode === '' || item.deliverable === null || item.deliverable === undefined || item.deliverable === '') {
            this.$tap.alert('第' + parseInt(i + 1) + '个里程碑' + (validateNull(item.milepostname) ? '' : item.milepostname) + '的必填字段请填写完整！', 'warning')
            this.submitLoading = false
            return false
          }
        }
        // 填写了客户决策链分析，校验鱼骨图必填
        this.model.taskidlist = []
        for (let taskItem of this.$refs.line.$refs.task) {
          for (let dataItem of taskItem.datas) {
            if (dataItem.post !== null && dataItem.post !== undefined && dataItem.post !== '' && (dataItem.taskstate === '0' || dataItem.taskstate === '1' || validateNull(dataItem.taskstate))) {
              this.model.taskidlist.push(dataItem.id + '')
            }
          }
        }
      }
      if (this.$refs.line && this.$refs.line.$refs.task) {
        for (let i = 0; i < this.$refs.line.$refs.task.length; i++) {
          if (this.$refs.line.$refs.task[i] && this.$refs.line.$refs.task[i].datas && this.$refs.line.$refs.task[i].datas.length > 0) {
            let tasks = this.$refs.line.$refs.task[i].datas
            for (let j = 0; j < tasks.length; j++) {
              if (tasks[j].responsible === null || tasks[j].responsible === undefined || tasks[j].responsible === '' || tasks[j].planstartdate === null || tasks[j].planstartdate === undefined || tasks[j].planstartdate === '' || tasks[j].planenddate === null || tasks[j].planenddate === undefined || tasks[j].planenddate === '') {
                this.$tap.alert('请填写任务责任人等信息！', 'warning')
                this.submitLoading = false
                return false
              }
              if (this.formatDateToMicro(this.$refs.line.milepostList[i].planfinishtime) < this.formatDateToMicro(tasks[j].planenddate)) {
                this.$tap.alert('任务计划结束日期不能大于里程碑及任务的计划达成日期！', 'warning')
                this.submitLoading = false
                return false
              }
              // 如果是短名单任务，将taskid赋值model字段
              if (tasks[j].dmdtask === 1) {
                this.$set(this.model, 'dmdtaskid', tasks[j].id)
              }
              // 短名单任务的客户决策分析是否全部填写完整
              if (tasks[j].dmdtask === 1 && (validateNull(tasks[j].post) || validateNull(tasks[j].customerapproval) || validateNull(tasks[j].customerattach) || validateNull(tasks[j].needsupport) || validateNull(tasks[j].improveplan))) {
                this.$tap.alert('里程碑及任务' + parseInt(i + 1) + '【' + this.$refs.line.milepostList[i].milepostname + '】下的任务' + parseInt(j + 1) + '【' + tasks[j].taskname + '】需填写客户决策分析信息！')
                this.submitLoading = false
                return false
              }
              // 保证用户填写客户决策分析任一内容，其他内容必须填写完整
              if ((validateNull(tasks[j].post) || validateNull(tasks[j].customerapproval) || validateNull(tasks[j].customerattach) || validateNull(tasks[j].needsupport) || validateNull(tasks[j].improveplan)) && (!validateNull(tasks[j].post) || !validateNull(tasks[j].customerapproval) || !validateNull(tasks[j].customerattach) || !validateNull(tasks[j].needsupport) || !validateNull(tasks[j].improveplan))) {
                this.$tap.alert('里程碑及任务' + parseInt(i + 1) + '【' + this.$refs.line.milepostList[i].milepostname + '】下的任务' + parseInt(j + 1) + '【' + tasks[j].taskname + '】的客户决策分析信息须填写完整！')
                this.submitLoading = false
                return false
              }
            }
          }
        }
      }
      return true
    },
    /** 格式化日期 **/
    formatDateToMicro(date) {
      return new Date(formatDate(new Date(date), 'yyyy-MM-dd')).getTime()
    },
    // 系统部监管任务的客户决策分析必填
    isValidateTask(taskname) {
      let indexFlag = -1
      this.codeModel.mpmsystemtasknameList.forEach((item, index) => {
        if (item.name === taskname) {
          indexFlag = index
        }
      })
      return indexFlag
    },
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    doexcelImport() {
      this.$refs.line.doexcelImport()
    },
    async doSubmitApproval() {
      if (!this.url.submit) {
        this.$tap.alert('请设置审批地址!', 'warning')
        return
      }
      let saveresult = await this.addBase()
      if (saveresult) {
        this.submitLoading = true
        this.$tap
          .confirm('确定提交审批吗？提交后，单据内容不可修改！')
          .then((_) => {
            if (!this.beforeApproval()) {
              this.submitLoading = false
              return
            }
            putAction(this.url.submit, this.model).then((res) => {
              if (res.success) {
                this.$tap.message(res.message, 'success')
                this.queryData(this.model.id)
                this.afterApproval()
              } else {
                this.$tap.alert(res.message, 'warning')
              }
              this.submitLoading = false
            })
          })
          .catch((_) => {
            this.submitLoading = false
          })
      }
    },
    async addBase() {
      if (this.beforeSubmit()) {
        this.saveLoading = true
        if (this.isAdd) {
          return await postAction(this.url.add, this.model)
            .then(async (res) => {
              if (res.success) {
                return await this.queryData(res.result.id).then(async (_) => {
                  this.isAdd = false
                  this.saveLoading = false
                  return await this.afterSubmit()
                    .then((_) => {
                      return true
                    })
                    .catch((_) => {
                      return false
                    })
                })
              } else {
                this.$tap.alert(res.message, 'warning')
                this.afterSubmit()
                this.saveLoading = false
                return false
              }
            })
            .catch((err) => {
              this.saveLoading = false
              return false
            })
        } else {
          return await putAction(this.url.edit, this.model)
            .then(async (res) => {
              if (res.success) {
                return await this.queryData(this.model.id).then(async (_) => {
                  this.isAdd = false
                  this.saveLoading = false
                  return await this.afterSubmit()
                    .then((_) => {
                      return true
                    })
                    .catch((_) => {
                      return false
                    })
                })
              } else {
                this.$tap.alert(res.message, 'warning')
                this.afterSubmit()
                this.saveLoading = false
                return false
              }
            })
            .catch((err) => {
              this.saveLoading = false
              return false
            })
        }
      }
    }
  }
}
</script>
<style scoped lang="scss">
/deep/.el-drawer {
  padding: 0 15px;
}
/deep/ .el-drawer__body {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  overflow: auto;
  border-top: 1px solid rgb(232, 232, 232);
}
.project-container .tl-form-line-titlemilepost {
  font-size: 18px;
  font-weight: bold;
  height: 32px;
  line-height: 20px;
  border-left: 4px solid #409eff;
  padding-left: 8px;
  margin: 17px 0 12px 15px;
  overflow: hidden;
}
</style>
